#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unordered_map>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
using namespace std;


struct User
{
    User(const string& ip,const uint16_t& port)
    :_ip(ip),_port(port)
    {}
    string _ip;
    uint16_t _port;
};


class onlineUser
{
public:
    onlineUser()
    {}
    void addUser(const string& ip,const uint16_t& port)
    {
        string id = ip + "-" + to_string(port);
        _mp.insert(make_pair(id,User(ip,port)));
    }
    void deleteUser(const string& ip,const uint16_t& port)
    {
        string id = ip + "-" + to_string(port);
        _mp.erase(id);
    }
    bool isOnline(const string& ip,const uint16_t& port)
    {
        string id = ip + "-" + to_string(port);
        auto it = _mp.find(id);
        return it != _mp.end()?true:false;
    }
    void broadcastMessage(int socketfd,const string& ip,const uint16_t& port,const string& message)
    {
        //把该ip的信息发给其他的ip用户
        for(auto& user:_mp)
        {
            struct sockaddr_in client;
            bzero(&client,sizeof(client));
            client.sin_family = AF_INET;
            client.sin_addr.s_addr = inet_addr(user.second._ip.c_str());
            client.sin_port = htons(user.second._port);
            //打包信息
            string s = ip + "-" + to_string(port) + "#";
            s += message;
            //发送给所有用户
            sendto(socketfd,s.c_str(),s.size(),0,(struct sockaddr*)&client,sizeof(client));
        }
    }
    ~onlineUser()
    {}
private:
    unordered_map<string,User> _mp; // 构造id和User之间的映射关系
};